﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using Microsoft.Practices.Unity;
using Microsoft.Practices.ServiceLocation;
using AzureGames.Web.UnityExtensions;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.ServiceRuntime;
using AzureGames.Domain.Services;
using AzureGames.Data;
using System.Web.Security;
using AzureGames.Web.Models;
using AzureGames.Model;
using System.Configuration;

namespace AzureGames.Web
{
    // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit http://go.microsoft.com/?LinkId=9394801

    public class MvcApplication : System.Web.HttpApplication
    {
        private static IUnityContainer container;

        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new HandleErrorAttribute());
        }

        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");


            routes.MapRoute(
                "Dashboard", // Route name
                "Dashboard", // URL with parameters
                new { controller = "Game", action = "List" } 
            );

            routes.MapRoute(
              "Default", // Route name
              "{controller}/{action}/{id}", // URL with parameters
              new { controller = "Game", action = "List", id = UrlParameter.Optional } // Parameter defaults
              );

        }

        public override void Init()
        {
            this.EndRequest += this.EndRequestHandler;
            base.Init();
        }

        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);

            InitializeDependencyInjectionContainer();
                   
            //FederatedAuthentication.ServiceConfigurationCreated += new EventHandler<Microsoft.IdentityModel.Web.Configuration.ServiceConfigurationCreatedEventArgs>(FederatedAuthentication_ServiceConfigurationCreated);

            CloudStorageAccount.SetConfigurationSettingPublisher((configName, configSetter) =>
            {
                // Provide the configSetter with the initial value
                configSetter(ConfigurationManager.AppSettings[configName]);
                
            });

            // start the notification service
            NotificationService.Instance.IntializeNotificationService(container.Resolve<INotificationRepository>(), (container.Resolve<IBoardRepository>()));
     
        }

        //protected void Session_Start()
        //{
        //    // start session to broadcast messages
        //    var notificationService = NotificationService.Instance.Create(container.Resolve<INotificationRepository>());
        //    notificationService.AddSession(HttpContext.Current.Session.SessionID, Guid.Empty.ToString());
        //}

        //protected void Session_End()
        //{
        //    // remove session to broadcast messages
        //    var notificationService = NotificationService.Instance;
        //    notificationService.RemoveSession(HttpContext.Current.Session.SessionID);
        //}

        private void PostAuthenticateRequestHandler(object sender, EventArgs e)
        {
            if (Request.IsAuthenticated)
            {
                // TODO: is there a cleaner way to detect when a session has expired
                //if(Session["User"]!=null)
                //{
                //var notificationService = new NotificationService(container.Resolve<INotificationRepository>());
                //notificationService.AddSession(HttpContext.Current.Session.SessionID, ((User)Session["User"]).ID);
                //}
            }
        }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability",
           "CA2000:Dispose objects before losing scope",
           Justification = "This should survive the lifetime of the application.")]
        private static void InitializeDependencyInjectionContainer()
        {
            container = new UnityContainerFactory().CreateConfiguredContainer();
            var serviceLocator = new UnityServiceLocator(container);
            ServiceLocator.SetLocatorProvider(() => serviceLocator);
            DependencyResolver.SetResolver(new UnityDependencyResolver(container));
        }

        private void EndRequestHandler(object sender, EventArgs e)
        {
            // This is a workaround since subscribing to HttpContext.Current.ApplicationInstance.EndRequest 
            // from HttpContext.Current.ApplicationInstance.BeginRequest does not work. 
            IEnumerable<UnityHttpContextPerRequestLifetimeManager> perRequestManagers =
                container.Registrations
                    .Select(r => r.LifetimeManager)
                    .OfType<UnityHttpContextPerRequestLifetimeManager>()
                    .ToArray();

            foreach (var manager in perRequestManagers)
            {
                manager.Dispose();
            }
        }

        //void FederatedAuthentication_ServiceConfigurationCreated(object sender, Microsoft.IdentityModel.Web.Configuration.ServiceConfigurationCreatedEventArgs e)
        //{
        //    List<CookieTransform> sessionTransforms =
        //            new List<CookieTransform>(new CookieTransform[] {
        //new DeflateCookieTransform(),
        //new RsaEncryptionCookieTransform(e.ServiceConfiguration.ServiceCertificate),
        //new RsaSignatureCookieTransform(e.ServiceConfiguration.ServiceCertificate)  });
        //    SessionSecurityTokenHandler sessionHandler = new SessionSecurityTokenHandler(sessionTransforms.AsReadOnly());
        //    e.ServiceConfiguration.SecurityTokenHandlers.AddOrReplace(sessionHandler);
        //}
    }
}
